package com.ts.api.http.market.channel;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.module.api.convert.core.annotation.ApiChannelMarket;
import com.ts.api.module.api.convert.core.annotation.ApiChannelMarketConvertType;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.market.entity.ChannelMarketParameter;
import com.ts.api.module.api.convert.market.handler.ChannelMarketConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Map;

/**
 *  淘宜融(晚上)
 *
 *  https://www.showdoc.com.cn/2598834544376057 密码 liandeng
 *
 *  @author WJB
 */
@ApiChannelMarket(uniqueCode = "ce4b3723d4954f10900ba97323599b07", type = ApiChannelMarketConvertType.FEDERATE_LOGIN)
public class TaoYiRongYeFederate implements ChannelMarketConvertHandler {

    private static final String PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDBmYNKnEdIUBpkWVF9ew7++JeUNfxhTFwK05T7q1PUpNwckseuKRjNsEDA6WxyZWE7eZhBDkASkrE+yPCIxNfZDDxmcUjuvPupYWetKZ7enfrWdNNHP3mTOmqVDIzc0QKsGiO/CsvroPEZyYcQS0XewHjN/Sn2+PR9FaE8IkwBWGaLPsCvWuPeX97fNNe8Z3lfW16Wig/+2Hvz+K/fGotmI0Tq1E7uIdWb/4tfLMG5q7nu/0m29wdsF+jgnGLMBJ2JyUY1oYm+XyaM/pVeRRrqxydC6MX0VG5qAeNpuPlcGavynCVrPWi3+HyiciEg3CL9s/gRdxI+WoHcWcPj787lAgMBAAECggEATd2nj7+xb+U/6DKAcx6mlmh31tWrz5p9vqEA4AQ1sGYqXZevll3TKw+Dy9NWm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6usoWjYY9fpYuK/+eSme1tqN55LraEK1ef6j9b+bBSJPmqEDC2gl5ZRg3n0J8Djcni8A6eCQ5w3nBZL5g==";

    @Override
    public ApiUserRequest parse(RequestVO requestVO) {
        String decryptData = decrypt(requestVO.getStr("content"), requestVO.getStr("key"), PRIVATE_KEY);
        JSONObject data = JSONObject.parseObject(decryptData);

        ApiUserRequest apiUserRequest = new ApiUserRequest();
        String phone = data.getString("phone");
        apiUserRequest.setPhone(phone);
        return apiUserRequest;
    }

    //  解密
    private static String decrypt(String encryptedData, String encryptedKey, String privateRSAKey) {
        try {
            return decryptData(encryptedData, encryptedKey, privateRSAKey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 解密aesKey原文
     *
     * @param encryptedKey 加密的aesKey
     * @param privateRSAKey rsa私钥
     * @return String
     * @throws Exception
     */
    private static String decryptKey(String encryptedKey, String privateRSAKey) throws Exception {
        byte[] privateKeyData = Base64.getDecoder().decode(privateRSAKey);
        byte[] encryptedAESKey = Base64.getDecoder().decode(encryptedKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyData));
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedAESKey = cipher.doFinal(encryptedAESKey);
        return Base64.getEncoder().encodeToString(decryptedAESKey);
    }

    /**
     * 解密JSON数据
     *
     * @param encryptedData 加密JSON数据
     * @param encryptedKey  加密key
     * @param privateRSAKey 私钥
     * @return String
     * @throws Exception
     */
    private static String decryptData(String encryptedData, String encryptedKey, String privateRSAKey) throws Exception {
        byte[] encryptJsonData = Base64.getDecoder().decode(encryptedData);
        String aesKey = decryptKey(encryptedKey, privateRSAKey);
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(aesKey), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedJson = cipher.doFinal(encryptJsonData);
        return new String(decryptedJson, StandardCharsets.UTF_8);
    }

    @Override
    public Map<String, Object> response(ChannelMarketParameter channelMarketParameter, ApiBizStatus apiBizStatus) {
        if (apiBizStatus.hasBizSuc()) {
            return MapUtils.newHashMap(newMap -> {
                newMap.put("code", 200);
                newMap.put("msg", apiBizStatus.getBizMsg());
                newMap.put("data", channelMarketParameter.getUrl());
            });
        }

        return MapUtils.newHashMap(newMap -> {
            newMap.put("code", 500);
            newMap.put("msg", apiBizStatus.getBizMsg());
        });
    }


}
